<template>
  <div style="position: relative">
    <el-form
      ref="formOrderField"
      :model="formOrderField"
      label-width="100px"
      size="mini"
      label-position="right"
      @submit.native.prevent
    >
      <filter-box :item-width="350">
        <el-form-item label="工单状态" prop="formFilter.flowStatus">
          <el-select
            class="filter-item"
            v-model="formOrderField.formFilter.flowStatus"
            :clearable="true"
            placeholder="工单状态"
          >
            <el-option
              v-for="item in SysFlowWorkOrderStatus.getList()"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期" prop="formFilter.createTime">
          <date-range
            class="filter-item"
            v-model="formOrderField.formFilter.createTime"
            :clearable="true"
            :allowTypes="['day']"
            align="left"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <!-- <el-form-item label="工单编号" prop="formFilter.workOrderCode">
          <el-input class="filter-item" v-model="formOrderField.formFilter.workOrderCode"
            :clearable="true" placeholder="工单编号"
          />
        </el-form-item> -->
        <!-- <el-button slot="operator" type="default" :plain="true" :size="defaultFormItemSize" @click="onReset">重置</el-button> -->
        <el-button
          slot="operator"
          type="primary"
          :plain="true"
          size="mini"
          @click="conditionQuery()"
          >查询</el-button
        >
        <el-button
          slot="operator"
          type="primary"
          size="mini"
          @click="onStartTaskClick()"
        >
          新建
        </el-button>
      </filter-box>
    </el-form>
    <el-row>
      <el-col :span="24">
        <el-table
          ref="fieldFlow"
          :data="meetRoomDataList"
          size="mini"
          @sort-change="fieldFlowWidget.onSortChange"
          header-cell-class-name="table-header-gray"
        >
          <el-table-column
            label="序号"
            header-align="center"
            align="center"
            type="index"
            width="100px"
            :index="getTableIndex"
          />
          <!-- <el-table-column label="工单编号" prop="workOrderCode" /> -->
          <el-table-column label="关联类型" prop="masterData.roomName">
          </el-table-column>
          <el-table-column label="申请日期" prop="masterData.applyDate">
            <template slot-scope="scope">
              <span>{{
                formatDateByStatsType(scope.row.masterData.applyDate, "day")
              }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="项目名称" prop="masterData.projectNameDictMap.name">
          </el-table-column> -->
          <el-table-column label="开始时间" prop="masterData.startTime">
            <template slot-scope="scope">
              <span>{{
                formatDateByStatsType(scope.row.masterData.startTime, "day")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" prop="masterData.endTime">
            <template slot-scope="scope">
              <span>{{
                formatDateByStatsType(scope.row.masterData.endTime, "day")
              }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="抵消打卡" prop="masterData.clockInDictMap.name">
          </el-table-column> -->
          <!-- <el-table-column label="当前任务" prop="runtimeTaskInfo.taskName" /> -->
          <el-table-column label="流程创建时间" prop="masterData.createTime" />
          <el-table-column
            label="流程状态"
            prop="flowStatus"
            width="100px"
          >
            <template slot-scope="scope">
              <span>{{SysFlowWorkOrderStatus.getValue(scope.row.flowStatus)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                v-if="
                  (scope.row.initTaskInfo || {}).taskKey ==
                  (scope.row.runtimeTaskInfo || {}).taskKey
                "
                @click.stop="onViewTaskClick(scope.row)"
              >
                详情
              </el-button>
              <el-button
                type="text"
                size="mini"
                v-if="
                  (scope.row.initTaskInfo || {}).taskKey !==
                  (scope.row.runtimeTaskInfo || {}).taskKey
                "
                @click.stop="onHandlerTaskClick(scope.row)"
              >
                办理
              </el-button>
              <el-button
                type="text"
                size="mini"
                v-if="
                  (scope.row.initTaskInfo || {}).taskKey !==
                  (scope.row.runtimeTaskInfo || {}).taskKey
                "
                class="table-btn"
                @click.stop="onRemindClick(scope.row)"
              >
                催办
              </el-button>
              <el-button
                type="text"
                size="mini"
                class="table-btn error"
                @click.stop="onCancelTaskClick(scope.row)"
              >
                撤销
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 10px">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { MeetRoom } from '@/api/approve.js';
import '@/staticDict/flowStaticDict.js'
import {
  TableWidget
} from '@/utils/widget.js'
import {
  uploadMixin,
  statsDateRangeMixin,
  cachePageMixin
} from '@/core/mixins'
// import { FieldFlowController } from '@/api'
import { FlowOperationController } from '@/api/flowController.js'
const processDefinitionKey = 'flowMeetRoom'
const processDefinitionName = '会议室申请'

export default {
  name: 'flowMeetRoom',
  props: {},
  mixins: [uploadMixin, statsDateRangeMixin, cachePageMixin],
  data () {
    return {
      meetRoomDataList: [], // 会议室审批列表list
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      formOrderField: {
        formFilter: {
          flowStatus: null, // 工单状态
          workOrderCode: '', // 工单编号
          createTime: []// 创建日期
        },
        formFilterCopy: {
          flowStatus: undefined,
          workOrderCode: undefined,
          createTime: []
        },
        isInit: false
      },
      fieldFlowWidget: new TableWidget(
        this.loadFieldFlowData,
        this.loadFieldFlowVerify,
        false
      ),
      workStateList: [
        { id: 1, name: '上班卡' },
        { id: 2, name: '下班卡' }
      ]
    }
  },
  methods: {
    // 获取会议室审批列表数据
    getList () {
      let params = {
        pageParam: {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        },
        flowWorkOrderDtoFilter: {
          flowStatus: this.formOrderField.formFilter.flowStatus,
          createTimeStart: this.formOrderField.formFilter.createTime[0],
          createTimeEnd: this.formOrderField.formFilter.createTime[1]
        },
        orderParam: [
          {
            fieldName: 'createTime',
            asc: false
          }
        ]
      }
      MeetRoom.list(this, params)
        .then((res) => {
          console.log('--------', res)
          this.meetRoomDataList = res.data.dataList
          this.total = res.data.totalCount
          // this.meetRoomDataList.forEach((item) => {
          //   this.$set(item.masterData, 'workStatusName', this.workStateList[(item.masterData.replacementType) - 1].name)
          // })
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 页面序号
    getTableIndex (index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
    },
    // 点击查询
    conditionQuery () {
      this.getList()
    },
    // onReset () {
    //   this.$refs.formOrderField.resetFields()
    //   this.refreshFormOrderField(true)
    // },
    loadFieldFlowData (params) {
      if (params == null) params = {}
      params = {
        ...params,
        flowWorkOrderDtoFilter: {
          flowStatus: this.formOrderField.formFilterCopy.flowStatus,
          workOrderCode: this.formOrderField.formFilterCopy.workOrderCode,
          createTimeStart: Array.isArray(
            this.formOrderField.formFilterCopy.createTime
          )
            ? this.formOrderField.formFilterCopy.createTime[0]
            : undefined,
          createTimeEnd: Array.isArray(
            this.formOrderField.formFilterCopy.createTime
          )
            ? this.formOrderField.formFilterCopy.createTime[1]
            : undefined
        }
      }
      // return new Promise((resolve, reject) => {
      //   FieldFlowController.list(this, params)
      //     .then((res) => {
      //       // let dataList = res.data.dataList.map((item) => {
      //       //   item.initTaskInfo = JSON.parse(item.initTaskInfo)
      //       //   item.runtimeTaskInfo = Array.isArray(item.runtimeTaskInfoList)
      //       //     ? item.runtimeTaskInfoList[0]
      //       //     : undefined
      //       //   item.masterData = item.masterData || {}
      //       //   return item
      //       // })
      //       resolve({
      //         dataList: res.data.dataList,
      //         totalCount: res.data.totalCount
      //       })
      //     })
      //     .catch((e) => {
      //       reject(e)
      //     })
      // })
    },
    loadFieldFlowVerify () {
      this.formOrderField.formFilterCopy.flowStatus =
        this.formOrderField.formFilter.flowStatus
      this.formOrderField.formFilterCopy.workOrderCode =
        this.formOrderField.formFilter.workOrderCode
      this.formOrderField.formFilterCopy.createTime =
        this.formOrderField.formFilter.createTime
      return true
    },
    // 新建会议室申请
    onStartTaskClick () {
      let params = {
        processDefinitionKey: processDefinitionKey
      }

      FlowOperationController.viewInitialTaskInfo(this, params)
        .then((res) => {
          if (
            res.data &&
            res.data.taskType === this.SysFlowTaskType.USER_TASK &&
            res.data.assignedMe
          ) {
            this.$router.push({
              name: res.data.routerName || 'MeetRoomAdd',
              query: {
                processDefinitionKey: processDefinitionKey,
                formId: res.data.formId,
                routerName: res.data.routerName,
                readOnly: res.data.readOnly,
                taskName: '启动流程',
                isDraft: true,
                flowEntryName: processDefinitionName,
                variableList: res.data.variableList,
                operationList: (res.data.operationList || []).filter((item) => {
                  return (
                    item.type !== this.SysFlowTaskOperationType.CO_SIGN &&
                    item.type !== this.SysFlowTaskOperationType.REVOKE
                  )
                })
              }
            })
          } else {
            FlowOperationController.startOnly(this, {
              processDefinitionKey: processDefinitionKey
            })
              .then((res) => {
                this.$message.success('启动成功！')
              })
              .catch((e) => {})
          }
        })
        .catch((e) => {})
    },
    // 办理流程
    onHandlerTaskClick (row) {
      let taskId =
        Array.isArray(row.runtimeTaskInfoList) &&
        row.runtimeTaskInfoList.length > 0
          ? row.runtimeTaskInfoList[0].taskId
          : undefined
      let params = {
        processInstanceId: row.processInstanceId,
        processDefinitionId: row.processDefinitionId,
        taskId: taskId
      }

      FlowOperationController.viewRuntimeTaskInfo(this, params)
        .then((res) => {
          if (res.data) {
            this.$router.push({
              name: res.data.routerName || 'RepairAdd',
              query: {
                isRuntime: true,
                isDraft: row.flowStatus === this.SysFlowWorkOrderStatus.DRAFT,
                taskId: taskId,
                processDefinitionKey: processDefinitionKey,
                processInstanceId: row.processInstanceId,
                processDefinitionId: row.processDefinitionId,
                formId: res.data.formId,
                routerName: res.data.routerName,
                readOnly: res.data.readOnly,
                taskName: (row.runtimeInitialTask || {}).taskName,
                flowEntryName: row.processDefinitionName,
                processInstanceInitiator: row.processInstanceInitiator,
                operationList: (res.data.operationList || []).filter((item) => {
                  return (
                    item.type !== this.SysFlowTaskOperationType.CO_SIGN &&
                    item.type !== this.SysFlowTaskOperationType.REVOKE
                  )
                }),
                variableList: res.data.variableList
              }
            })
          }
        })
        .catch((e) => {})
    },
    // 查看流程
    onViewTaskClick (row) {
      let params = {
        id: row.businessKey,
        processInstanceId: row.processInstanceId
      }
      let taskId =
        Array.isArray(row.runtimeTaskInfoList) &&
        row.runtimeTaskInfoList.length > 0
          ? row.runtimeTaskInfoList[0].taskId
          : undefined
      MeetRoom.detail(this, params)
        .then((res) => {
          if (res.data) {
            this.$router.push({
              name: res.data.routerName || 'MeetRoomDetail',
              path: '/MeetRoomApproval/Detail:params',
              query: {
                isRuntime: false,
                taskId: taskId,
                processDefinitionKey: row.processDefinitionKey,
                processInstanceId: row.processInstanceId,
                processDefinitionId: row.processDefinitionId,
                routerName: res.data.routerName,
                readOnly: true,
                flowEntryName: row.processDefinitionName,
                processInstanceInitiator: row.processInstanceInitiator,
                masterData: row.masterData, // 当前行数据
                id: row.businessKey
              }
            })
          }
        })
        .catch((e) => {})
    },
    // 催办
    onRemindClick (row) {
      FlowOperationController.remindRuntimeTask(this, {
        workOrderId: row.workOrderId
      })
        .then((res) => {
          this.$message.success('催办成功')
        })
        .catch((e) => {})
    },
    // 撤销流程
    onCancelTaskClick (row) {
      console.log('撤销', row)
      this.$confirm('是否撤销此工单？')
        .then((res) => {
          let params = {
            workOrderId: row.workOrderId,
            cancelReason: '主动撤销'
          }

          FlowOperationController.cancelWorkOrder(this, params)
            .then((res) => {
              this.$message.success('撤销成功！')
              this.getList()
            })
            .catch((e) => {})
        })
        .catch((e) => {})
    }
  },
  mounted () {
    // 获取列表数据
    this.getList()
  },
  watch: {
    $route () {
      this.getList()
    }
  }
}
</script>

<style></style>
